<?php
namespace app\draw\controller;
use think\Cache;
use think\Controller;
use think\Db;
use app\common\model\ApplyLog;
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/15
 * Time: 10:03
 */

class Draw extends Controller
{
    public function index($member_id = 0){

        $data = Db::name('draw')->order(['probability' => 'desc'])->where('auding_status',2)->where('is_delete',1)->select();
        $color = [];
        foreach ($data as $k => $v){
            // $col = ["#FFF4D6", "#FFFFFF"];
            $col = ["#ff6666", "#fb3c45"];
            array_push($color,$col[$k%2]);
            if(count($data)%2 == 1 && $k == count($data)-1){
                $color[count($data)-1] = "#ff1433";
            }

        }
        // $color = ["#FFF4D6", "#FFFFFF", "#FFF4D6", "#FFFFFF","#FFF4E6", "#FFFFFF", "#FFF4D6", "#FFFFFF","#FFF4D6", "#FFFFFF"];
        $draw_records = Db::name('draw_records dr')
            ->join('member m','m.id = dr.member_id')
            ->join('draw d','dr.draw_id = d.id')
            ->field('title,username')
            ->select();


        $remark = Db::name('about')->where('id',6)->value('content');
        return view('',['data' => json_encode($data),'color' => json_encode($color),'draw_records' => $draw_records,'web_title' => '小毛驴车管家','remark' => $remark]);
    }


    public function get_rand($member_id = 0,$name,$phone,$id_number,$draw_id) {

        $result['key'] = 0;
        $result['data'] = [];
        $result['code'] = 200;
        if(empty($member_id)){
            $result['code'] = 0;
            $result['message'] = '必须是会员才能抽奖';
            return $result;
        }

        $draw_number = Db::name('draw_number')->where('member_id',$member_id)->value('count');
        if($draw_number <= 0){
            $result['code'] = 0;
            $result['message'] = '抽奖次数不足';
            return $result;
        }

       Db::name('draw_number')->where('member_id',$member_id)->setDec('count');
        $draw_time = (new Draw())->haha_kaijiang();
        writeLog('get_rand'.json_encode($draw_time));
        //$data = Db::name('draw_time_gift')->where('draw_id',$draw_time['id'])->select();
        //$data = Db::name('draw')->order(['probability' => 'desc'])->select();
        //$proArr = Db::name('draw')->order(['probability' => 'desc'])->column('probability');
        $data = Db::name('draw_time_gift')->where('draw_id',$draw_time['id'])->select();//当前活动所有奖品

        $proArr = Db::name('draw_time_gift')->where('draw_id',$draw_time['id'])->column('draw_probability');//当前活动所有奖品概率

        $proSum = array_sum($proArr);
        writeLog('start');
        writeLog('开局总概率和'.$proSum);
        $i = 0;
        $j = 0;
        //概率数组循环
        foreach ($proArr as $key => $proCur) { //奖品概率数组循环
            $randNum = mt_rand(1, $proSum);//1到总概率随机数
            writeLog('ifesle之前随机数'.$randNum);
            if ($randNum <= $proCur) {
                $i++;

                writeLog('随机数'.$randNum.'-当前概率数据'.$proCur.'-总概率和'.$proSum);
                $result['key'] = $key;
                $result['data'] = $data[$key];
                //$max = Db::name('draw')->max('probability');

                $max = Db::name('draw_time_gift')->where('draw_id',$draw_time['id'])->max('draw_probability');

                if($data[$key]['draw_probability'] < $max){ //当前奖品概率小于最大的奖品概率为中奖  非第一个奖品的能走进来肯定都是小于的
                    writeLog('随机种');
                    //抽奖记录显示
                    $ret = Db::name('draw_records')->where('member_id',$member_id)->insert([
                        'draw_id' =>$draw_id,
                        'draw_title' =>$data[$key]['draw_title'],
                        'member_id' => $member_id,
                        'name' => $name,
                        'phone' => $phone,
                        'id_number' => $id_number,
                        'create_time' => date('Y-m-d H:i:s',time())
                    ]);
                    writeLog('中奖records'.$ret);
                    //抽奖信息添加
                    $ret_mm = Db::name('member_message')->insert([
                            'member_id' => $member_id,
                            'create_time' => date('Y-m-d H:i:s',time()),
                            'title' => '您已中奖,请前往门店兑奖',
                            'content' => '恭喜用户 '.$phone.' 获取 '.$data[$key]['draw_title'].' 奖品',
                            'message_type' => 2,
                            'type_id' => 1
                        ]
                    );
                    writeLog('中奖mm'.$ret_mm);

                    //禁止抛出异常;
                    $m = (new \app\index\controller\MemberMessage())->jpushMessage($member_id,'您已中奖,请前往门店兑奖','恭喜用户 '.$phone.' 获取 '.$data[$key]['draw_title'].' 奖品',1);

                }else{ //最大概率非中奖$data[$key]['draw_title']写死下次再来
                    writeLog('非中奖');
                    $ret = Db::name('draw_records')->where('member_id',$member_id)->insert([
                        'draw_id' =>$draw_id,
                        'draw_title' =>'下次再来',
                        'member_id' => $member_id,
                        'name' => $name,
                        'phone' => $phone,
                        'id_number' => $id_number,
                        'create_time' => date('Y-m-d H:i:s',time())
                    ]);
                    writeLog('非中奖records'.$ret);
                    //抽奖信息添加
                    $ret_mm = Db::name('member_message')->insert([
                            'member_id' => $member_id,
                            'create_time' => date('Y-m-d H:i:s',time()),
                            'title' => '本次抽奖结束,您未中奖',
                            'content' => '活动主题:'.$draw_time['title'],
                            'message_type' => 3,
                            'type_id' => 1
                        ]
                    );
                    writeLog('非中奖mm'.$ret_mm);
                    //禁止抛出异常;
                    $ret_m =(new \app\index\controller\MemberMessage())->jpushMessage($member_id,'本次抽奖结束,您未中奖','活动主题:'.$draw_time['title'],1);
                    writeLog('非中奖极光'.$ret_m);
                }

                break;
            } else {
                writeLog('else');
                $j++;
                writeLog('else当前概率数据'.$proCur);
                $proSum -= $proCur;
            }
        }
        write_log('完毕');
        writeLog('i+j '.$i.'-'.$j);
        writeLog('end');
        unset ($proArr);

        return $result;

    }

    public function abc(){
        $draw_time = (new Draw())->haha();
        $data = Db::name('draw_time_gift')->where('draw_id',$draw_time['id'])->select();
        //$data = Db::name('draw')->order(['probability' => 'desc'])->select();
        //$proArr = Db::name('draw')->order(['probability' => 'desc'])->column('probability');
        $data = Db::name('draw_time_gift')->where('draw_id',$draw_time['id'])->select();//当前活动所有奖品
        $proArr = Db::name('draw_time_gift')->where('draw_id',$draw_time['id'])->column('draw_probability');//当前活动所有奖品

    }

    /**
     * @param $member_id
     *
     * 会员抽奖次数 这个接口用来判断进步进入 报名接口
     */
    public function count($member_id){

        $count = Db::name('draw_number')->where('member_id',$member_id)->value('count');
        $count = is_null($count) ? 0 : $count;
        //系统配置
        //$draw = Db::name('config')->where('varname','web_draw')->value('varvalue');
        $is_certification = Db::name('member')->where('id',$member_id)->value('is_certification');
        if($is_certification != 2){
            return json(['code' => 400,'message' => '未实名认证成功']);
        }
        $draw_time = $this->haha();//当前抽奖活动
        if(is_null($draw_time)){
            $draw_time = 'N';
        }else{
            $draw_time = 'Y';
        }
        if($count>0){
            $model = new ApplyLog();
            $data = $model
                ->where(['member_id'=>$member_id])
                ->field('name,id_card,phone')
                ->where('status',1)
                //->where('draw_id',$this->haha()['id'])
                ->find();
            if(empty($data)){
                $data = [
                    'name' => '',
                    'id_card' => '',
                    'phone' => '',
                ];
            }
        }else{
            $data = [
                'name' => '',
                'id_card' => '',
                'phone' => '',
            ];
        }
        $draw_time = $this->haha();
        $apply_count = Db::name('apply_log')->where('draw_id',$draw_time['id'])->count();
        if($apply_count >= $draw_time['apply_number']){
            return json(['code' => 400,'message' => '本次抽奖报名人数已满,下次再来']);
        }

        return json(['code' => 200,'message' => '会员剩余抽奖次数','count' => $count,'apply_info'=>$data,'draw'=>$draw_time]);
    }

    /**
     * @return array|false|\PDOStatement|string|\think\Model
     * 报名区间
     */
    public function haha(){
        $draw_time = Db::name('draw_time')
            ->order('draw_start_time','asc')
            ->whereTime('apply_start_time','<',time())
            ->whereTime('apply_end_time','>',time())
            ->where('status',1)
            ->where('auding_status',2)->where('is_delete',1)
            ->whereTime('draw_start_time','>',time())
            ->find();//报名时间必须小于开奖时间
        return $draw_time;
    }

    /**
     * @return array|false|\PDOStatement|string|\think\Model
     * 开奖区间
     */
    public function haha_kaijiang(){  //开奖时间
        $draw_time = Db::name('draw_time')
            ->order('draw_start_time','asc')
            ->whereTime('apply_start_time','<',time())
            ->whereTime('apply_end_time','>',time())
            ->where('status',1)
            ->where('auding_status',2)->where('is_delete',1)
            ->whereTime('draw_start_time','>',time()-600)
            ->find();//报名时间必须小于开奖时间
        return $draw_time;
    }
    public function hahaj(){
        $time = date('Y-m-d H:i:s',time());
        $draw_time = Db::name('draw_time')
            ->order('draw_start_time','asc')
            ->whereTime('apply_start_time','<',$time)
            ->whereTime('apply_end_time','>',$time)
            ->whereTime('draw_start_time','>',time())
            ->where('status',1)
            ->find();
        return json($draw_time);
    }

    /**
     * 立即报名
     */
    public function apply()
    {

        try{
            $param = request()->param();

            $results = $this->validate($param,'Draw.apply');
            if($results!==true){
                return json(['code'=>400,'message'=>$results]);
            }
            $member_id = $param['member_id'];
            //系统配置

            $draw_time = $this->haha();
            //当前抽奖活动
            if(is_null($draw_time)){
                $apply_bool = 'N';
            }else{
                $apply_bool = 'Y';
            }
            // $apply_bool = Db::name('config')->where('varname','apply_bool')->value('varvalue');
            if($apply_bool =="N"){
                return json(['code' => 400,'message' => '报名状态未开启!']);
            }

            $model = new ApplyLog();
            //判断是否有已经报名的题目
            $map = [
                'status' => 1,
                'member_id' => $member_id,
//                'draw_id' => $draw_time['id']
            ];
            $res = $model->where($map)->find();
            if($res){

                return json(['code' => 400,'message' => '已经报名,请等待开奖!']);
            }
            $apply_count = Db::name('apply_log')->where('draw_id',$draw_time['id'])->count();
            if($apply_count >= $draw_time['apply_number']){
                return json(['code' => 400,'message' => '本次抽奖报名人数已满,下次再来']);
            }
            $param['create_time'] = time();
            $param['draw_id'] = $draw_time['id'];
            //新增
            $model->allowField(true)->save($param);
            //判断有多少报名的未通知的
            $count = $model->where('status',1)->count('id');
            //系统配置
            // $web_number = Db::name('config')->where('varname','apply_number')->value('varvalue');
            $web_number  = $draw_time['apply_number'];
            if($count>=$web_number){
                //需要通知客户
            }
            //$time = Db::name('config')->where('varname','web_draw_time')->value('varvalue');
            $start_time = $this->haha();
            return json(['code'=>200,'message'=>'报名成功,开奖时间:'.$start_time['draw_start_time']]);
            //return json(['code'=>200,'message'=>'报名成功']);

        }catch (\Exception $exception){
            return json(['code' => 400,'message' => $exception->getMessage()]);
        }
    }

    /**
     * 定时任务使用;
     */
    public function get_draw_time()
    {
        Db::name('content')->insert(['create_time' => date('Y-m-d H:i:s',time())]);
        $draw_time = Db::name('draw_time')
            ->order('draw_start_time', 'asc')
            ->whereTime('apply_start_time', '<', time())
            ->whereTime('apply_end_time', '>', time())
            ->where('status', 1)
            ->where('auding_status', 2)->where('is_delete', 1)
            ->whereTime('draw_start_time', '>', time() - 600)
            ->find();
        // 1.开奖时间大于当前延迟5分钟内时间都属于 true 比如12点开奖时间 12点05之前都一直调用
        // 2.开将时间小等于当前时间并且大等于 12点以上才会 draw_start_time>=12点 &&  draw_start_time <= 12.05 当前时间减去5分钟
        //可能12.03进来 draw_start_time <= time() 12.03 && draw_start_time >= time()-600 11.58;
        $people = Db::name('apply_log')->where('draw_id', $draw_time['id'])->count();
        //当前抽奖活动
        writeLog('get_draw_time' . json_encode($draw_time));
        if (is_null($draw_time)) {
            return;
            $apply_bool = 'N';
        } else {
            $apply_bool = 'Y';
        }
        $web_draw_time = strtotime($draw_time['draw_start_time']);//开奖时间

        $time = time();
        //计划任务3分钟 5分钟内才可以 所有进入1次
        if ($time >= $web_draw_time && $web_draw_time + 600 >= $time && $people >= $draw_time['apply_number']) { //当前时间大等于 开奖时间 就是可以开奖了

            writeLog('定时进来');

            $draw_time = Cache::get($web_draw_time);
            dump($draw_time);
            if (!empty($draw_time)) {
                writeLog('停止' . date('Y-m-d H:i:s', $draw_time) . '-当前时间' . date('Y-m-d H:i:s', time()));
                return;
                writeLog('return');
            }
            $t = Cache::set($web_draw_time, $web_draw_time);
            dump($t);
            writeLog('定时第一次进来');
            $this->get_rand_time();

        } else {
            writeLog('定时任务时间失败' . date('Y-m-d H:i:s', time()));
        }
    }

    public function get_rand_time()
    {

        Db::startTrans();
        try {
            $draw = $this->haha_kaijiang();
            writeLog('get_rand_time'.json_encode($draw));
            $rand_data = Db::name('apply_log al')
                ->join('draw_time dt', 'al.draw_id = dt.id','left')
                ->join('draw_time_gift dtg','dtg.id = al.draw_prize','left')
                ->field('al.*,dt.title,dtg.draw_title title,dtg.draw_probability')
                ->where('al.draw_prize', 'eq', 0)
                ->where('al.draw_id',$draw['id'])
                ->where('dt.auding_status',2)->where('dt.is_delete',1)
                ->fetchSql(false)
                ->select();
            //这些是随机中奖的用户
            if (!empty($rand_data)) {
                foreach ($rand_data as $k => $v) {
                    $ret = $this->get_rand($v['member_id'], $v['name'], $v['phone'],$v['id_card'],$v['draw_id']);
                    Db::name('apply_log')->where('id',$v['id'])->setField('status',2);
                    write_log('ret'.json_encode($ret));
                }
            }

            $must_data = Db::name('apply_log al')
                ->join('draw_time dt', 'al.draw_id = dt.id','left')
                ->join('draw_time_gift dtg','dtg.id = al.draw_prize')
                ->field('al.*,dt.title,dtg.draw_title title,dtg.draw_probability')
                ->where('draw_prize', 'gt', 0)
                ->where('al.draw_id',$draw['id'])
                ->where('dt.auding_status',2)->where('dt.is_delete',1)
                ->select();

            //必中奖的用户->where('al.status', 1)
            if (!empty($must_data)) {
                foreach ($must_data as $k1 => $v1) {
                    $ret = Db::name('draw_records')->where('member_id', $v1['member_id'])->insert([
                        'draw_id' => $v1['draw_id'],
                        'draw_title' => $v1['title'],
                        'member_id' => $v1['member_id'],
                        'name' => $v1['name'],
                        'phone' => $v1['phone'],
                        'id_number' => $v1['id_card'],
                        'create_time' => date('Y-m-d H:i:s', time())
                    ]);
                    //抽奖信息添加
                    Db::name('member_message')->insert([
                            'member_id' => $v1['member_id'],
                            'create_time' => date('Y-m-d H:i:s', time()),
                            'title' => '您已中奖,请前往门店兑奖',
                            'content' => '恭喜用户 ' . $v1['phone'] . ' 获取 ' . $v1['title'] . ' 奖品',
                            'message_type' => 2,
                            'type_id' => 1
                        ]
                    );
                    Db::name('apply_log')->where('id',$v1['id'])->setField('status',2);
                    Db::name('draw_number')->where('member_id',$v1['member_id'])->setDec('count');
                    (new \app\index\controller\MemberMessage())->jpushMessage($v1['member_id'], '您已中奖,请前往门店兑奖', '恭喜用户 ' . $v1['phone'] . ' 获取 ' . $v1['title'] . ' 奖品', 1);
                    write_log('必中'.json_encode($v1));
                }

            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => $e->getCode(),'message' => $e->getMessage(),'line' => $e->getLine()]);
        }

    }
}